<?php
/**
 * 日志类
 *
 * @package Log
 * @author shukyyang
 * @version $Id$
 */
namespace SF;

class Log
{
    /**
     * 普通信息记录
     *
     * @param string|array $content 内容
     * @param string $file_path 日志文件路径
     */
    public static function logInfo($content, $file_path)
    {
        $data = '';
        if (is_array($content)) {
            foreach ($content as $key=>$value) {
                $data .= $key .'['. trim($value) .']';
            }
        } else {
            $data = (string)$content;
        }
        $data = 'T['. date('Y-m-d H:i:s') .'] '. $data ."\r\n";
        self::write($data, $file_path);
    }

    /**
     * 写入日志
     *
     * @param string $content
     * @param string $file_path
     */
    public static function write($content, $file_path)
    {
        if (!is_dir(dirname($file_path))) {
            self::createDir(dirname($file_path));
        }
        if (!$handle = fopen($file_path, 'a+b')) {
            require_once SF_PATH .'/Exception';
            throw new \SF\Exception('无法打开文件');
        }
        flock($handle, LOCK_EX);
        fwrite($handle, $content);
        flock($handle, LOCK_UN);
        fclose($handle);
    }

    /**
     * 递归创建文件夹
     *
     * @param string $dir_path 目录路径
     * @param int $lv 限制的目录深度
     */
    public static function createDir($dir_path, $lv = 5)
    {
        if (!is_dir($dir_path) && $lv > 0) {
            $lv--;
            self::createDir(dirname($dir_path), $lv);
            @mkdir($dir_path, 0777);
        }
    }

}